<?php
namespace HttpRequester;

use HttpRequester\Curl;

class CurlProxy extends Curl
{
    /**
     * proxy
     *
     * @var string
     */
    private $proxy;

    /**
     * constructor
     *
     * @param string $proxy
     */
    public function __construct($proxy)
    {
        $this->proxy = $proxy;
    }

    /**
     * request via proxy
     *
     * @param  string $url
     * @param  string $method
     * @param  array|string $post_data
     * @param  array  $options
     * @return mixed
     */
    public function request($url, $method = 'get', $post_data = null, array $options = [])
    {
        if(!static::isValidProxyFormat($this->proxy)){
            $this->setError('proxy is not set or param has invalid format', 'using_proxy');
        }else{
            $options = array_replace($options, [CURLOPT_PROXY => $this->proxy]);
        }
        return parent::request($url, $method, $post_data, $options);
    }

    /**
     * getProxy
     *
     * @return string|null
     */
    public function getProxy(){
        return $this->proxy;
    }

    /**
     * setProxy
     *
     * @param string $proxy
     * @return $this
     */
    public function setProxy($proxy)
    {
        if(static::isValidProxyFormat($proxy)){
            $this->proxy = $proxy;
        }
        return $this;
    }

    /**
     * isValidProxyFormat
     *
     * @param  string  $proxy
     * @return boolean
     */
    public static function isValidProxyFormat($proxy)
    {
        return (bool) preg_match('/^(?:\d{1,3}\.){3}(?:\d{1,3}(?:\:\d{2,5}))$/', $proxy);
    }
}
